import React, { Component } from 'react'
import {
  View,
  StyleSheet,
  Image,
  Text,
  TouchableOpacity,
  FlatList,
  ActivityIndicator,
  RefreshControl
} from 'react-native'
import {
  width,
  statusBarHeight,
} from '../utils/Global';
import {
  POST_USER_SOCIALCIRCLE_PRAISE,
  GET_QUERYMINE_LIST
} from '../public/WebApi/socialcircleApi'
import fetchWebApi from '../public/WebApi/fetchBase';
import getStorageValue from '../utils/getStorageValue';
import { Constant } from '../public/js/constant';
import Layer from "../utils/Layer";
import AsyncStorage from '@react-native-community/async-storage';
export default class MySocialCircle extends Component {
  constructor(props) {
    super(props)
    this.isLoadingMore = false;
    this.state = {
      currentTab: 0,
      mySocialCircleList: [],
      mySocialCircleListFriend: [],
      //社圈数据
      defaultTab: true,
      selectImage1: [],
      isLoading: false,
      page: 0,
      pageSize: 5,
      tempAddDatas: [],
      isRefreshing: false,
      status: 1
    }
  }

  componentDidMount = () => {
    this.getSocialCircleList()
  }

  async getSocialCircleList() {
    const { userInfoId } = this.props
    const res = await fetchWebApi(GET_QUERYMINE_LIST, {
      token: await getStorageValue(Constant.TOKEN),
      page: this.state.page,
      pageSize: this.state.pageSize,
      userInfoId: userInfoId
    }, 'POST');
    // console.log('############## getSocialCirclelist');
    // console.log(res);
    if (res.status == 200) {
      // res.data.businessList.map((item, index) => {
      //   this.state.mySocialCircleList.push(item)
      // })
      if (res.data == null) {
        this.setState({
          status: 0
        })
        return;
      }
      if (this.state.page == 0) {
        this.setState({
          mySocialCircleList: res.data.businessList
        })
      } else {
        this.setState({
          tempAddDatas: res.data.businessList
        })
      }

      if (res.data.businessList.length == 0) {
        this.setState({
          status: 0
        })
        return;
      }
      console.log(this.state.mySocialCircleList);
      this.setState({
        page: this.state.page + this.state.pageSize
      })
    } else {
      Layer.showMsg("获取用户信息列表失败");
    }
    // console.log(this.state.mySocialCircleList.length);


  }

  async postSocialCirclePraise(item) {
    const res = await fetchWebApi(POST_USER_SOCIALCIRCLE_PRAISE, {
      token: await getStorageValue(Constant.TOKEN),
      businessId: item
    }, 'POST');
    // console.log("########## postSocialCircleListPraise");
    // console.log(res);
    if (res.status == 200) {
      this.setState({
        // businessId: res.data
      })
      this.getSocialCircleList()
      // this.getSocialCircleListFriend()
    } else {
      Layer.showMsg("获取用户信息列表失败");
    }
  }

  handleRefresh = () => {
    this.setState({
      page: 0,
      isRefreshing: true,//tag,下拉刷新中，加载完全，就设置成flase
      mySocialCircleList: []
    });
    this.getSocialCircleList()
    this.setState({
      isRefreshing: false,
      status: 1
    })
  }

  genIndicator() {
    return <View style={styles.IndicatorContainer}>
      <ActivityIndicator  //显示一个圆形的 loading 提示符号。
        style={styles.Indicator}
        size={"small"}
        animating={true}
        color={'gray'}
      />
      <Text>正在加载更多</Text>
    </View>
  }

  loadData(pullUp) {
    if (this.isLoadingMore) {
      return;
    }
    this.isLoadingMore = true;
    this.getSocialCircleList().then(() => {
      var dataArray = []
      // var page = 0
      // if (pullUp) {

      dataArray = this.state.mySocialCircleList,
        dataArray = [...this.state.mySocialCircleList, ...this.state.tempAddDatas]

      // }
      this.setState({
        mySocialCircleList: dataArray,
        isLoading: false,
      })
      this.isLoadingMore = false;
    })


  }


  _renderItem1(data) {
    const { SocialCircleThis } = this.props
    // console.log(data.item);
    return (
      // <>
      //   {
      //     data
      //       .map((item, index) => (
      <View style={styles.mySocialCircle} >
        <View style={styles.uploadBoxContainer}>
          <TouchableOpacity onPress={() => {
            SocialCircleThis.props.navigation.push('socialcircleDetails', { businessId: data.item.businessId })
          }}>
            <View style={styles.uploadBoxHeadPortrait}>
              <View style={styles.headPortraitBox}>
                <Image
                  source={data.item.userInfoAvatar == null ? require("../assets/images/socialcircle/defaultHeadpor.png") : { uri: data.item.userInfoAvatar }}
                  style={styles.headPortrait}
                />
              </View>

              <View style={styles.headPortraitText}>
                <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-start' }}>
                  <Text style={styles.headPortraitName}>
                    {data.item.userInfoName}
                  </Text>
                  <Image style={{ marginTop: 3, marginLeft: 3, width: 18, height: 18 }} source={data.item.userType == 1 ? require('../assets/images/maillist/enterprise.png') : null} />
                </View>
                <Text style={styles.headPortraitTime}>
                  {data.item.businessCreateTime}
                </Text>
              </View>
            </View>
            {/* 社圈标题 */}
            {data.item.businessTitle != '' ? <View style={styles.textContent}>
              <Text style={styles.textTitleTexts}>
                {data.item.businessTitle}
              </Text>

            </View> : null}
            {/* 标签 */}
            {data.item.businessLabel != null && data.item.businessLabel.length != 0 ? <View style={styles.labelRow}>
              {data.item.businessLabel.map((item, index) => (
                <View key={index} style={{ backgroundColor: "rgba(223,239,255, 0.19)", paddingLeft: 2, paddingRight: 2, justifyContent: 'center', alignItems: 'center', marginRight: 5, borderColor: 'rgba(24, 144, 255, 1)', borderWidth: 1, borderRadius: 2 }}>
                  <Text style={styles.textContentLabel}>
                    #{item}
                  </Text>
                </View>
              ))}
            </View> : null}
            {data.item.businessFilePath != null && data.item.businessFilePath.length != 0 ? <View style={styles.row}>
              {/* 发布的图片 */}
              {data.item.businessFilePath.slice(0, 3).map((item, index) => (
                <View style={(index + 1) % 3 == 0 ? styles.item : styles.itemMr} key={index}>
                  <Image
                    style={styles.SystemPrompt}
                    source={{ uri: item }}
                  />
                </View>
              ))}
            </View> : null}
            {/* 定位信息 */}
            {data.item.place ? <TouchableOpacity style={styles.locationBox}>
              <Image source={require("../assets/images/socialcircle/location2.png")} style={styles.locationBoxImage}></Image>
              <Text style={styles.locationBoxFont}>
                {data.item.place}
              </Text>
            </TouchableOpacity> : <View style={{ margin: 3 }}></View>}

            {/* 阅读数量 */}
            <View style={styles.timesBox}>
              <View style={styles.timesViews}>
                <Image source={require("../assets/images/socialcircle/browse.png")} style={styles.timesViewsImage}></Image>
                <Text style={styles.timesViewsFont}>
                  {data.item.countBrowse} 阅读
                </Text>
              </View>
              <View style={styles.likeCommentBox}>
                {/* 喜欢数量 */}
                <View style={styles.likeBox} onPress={() => {
                  // console.log(item.businessId);
                  this.postSocialCirclePraise(data.item.businessId)
                  this.setState({
                    // flag: item.likeFlag = !item.likeFlag
                  })
                }}>
                  <Image source={data.item.ifCount == 1 == true ? require("../assets/images/socialcircle/like.png") : require("../assets/images/socialcircle/like_off.png")} style={styles.likeBoxImage}></Image>
                  <Text style={styles.likeBoxFont}>
                    {data.item.countGive}
                  </Text>
                </View>
                {/* 评论数 */}
                <View style={styles.commentBox}>
                  <Image source={require("../assets/images/socialcircle/comment.png")} style={styles.commentBoxImage}></Image>
                  <Text style={styles.commentBoxFont}>
                    {data.item.countComments}
                  </Text>
                </View>
              </View>
            </View>
          </TouchableOpacity>

        </View>
      </View>
      //       ))}
      // </>
    )
  }

  render() {
    //社圈组件封装
    const mySocialCircle =
      <>
        {/* 底部提示 */}
        <View style={styles.bottom_container}>
          <Text style={styles.bottom_text}>没有更多了哦~</Text>
        </View>
      </>

    return (
      <View style={styles.container} >
        {/* <View style={styles.statusBar} /> */}

        {/* 头部内容 */}
        {/* <View style={styles.header}>
        </View > */}
        <FlatList
          // showsVerticalScrollIndicator={false}
          // refreshing={this.refreshing}
          data={this.state.mySocialCircleList}
          renderItem={(data) => this._renderItem1(data)}
          keyExtractor={(item, index) => { item.businessId, index.toString() }}
          numColumns={1}//一行一列
          ListFooterComponent={() =>
            this.state.status == 1 ? this.genIndicator() : mySocialCircle
          }//底部组件
          onEndReached={//列表被滚动到距离内容最底部不足onEndReachedThreshold设置的的距离时调用。
            () => {
              this.loadData(true);
            }
          }
          onEndReachedThreshold={0.01}//0.5 表示距离内容最底部的距离为当前列表可见长度的一半时触发onEndReached回调
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
              colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
              progressBackgroundColor="#ffffff"
            />
          }
        // contentContainerStyle={{ flex: 1 }}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    height: "100%"
  },
  header: {
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingLeft: 15,
    paddingRight: 15,
    // backgroundColor: "red"
  },
  mySocialCircle: {
    display: "flex",
    backgroundColor: "white",
    borderRadius: 10,
    margin: 15
  },
  uploadBoxContainer: {
    padding: 15,
    display: "flex",
  },
  uploadBoxHeadPortrait: {
    display: "flex",
    flexDirection: "row",
    marginBottom: 10,
  },
  headPortraitBox: {
    width: 50,
    height: 50,
    borderRadius: 25,
  },
  headPortrait: {
    width: 50,
    height: 50,
    borderRadius: 25,
    // borderRadius: 50,
    // resizeMode: "contain"
  },
  headPortraitText: {
    height: 50,
    lineHeight: 50,
    marginLeft: 15
  },
  headPortraitName: {
    height: 25,
    lineHeight: 25,
    fontWeight: 'bold',
    fontSize: 16
  },
  headPortraitTime: {
    height: 25,
    lineHeight: 25,
    color: "rgba(0,0,0,0.4)",
    fontSize: 13
  },
  textContent: {
    flexDirection: "row",
    alignItems: "center",
    flexWrap: "wrap",
    marginBottom: 10,
    fontWeight: '700',
  },
  textTitleTexts: {
    // marginRight: 10,
    fontSize: 17,
    // marginBottom: 10,
  },
  textContentLabel: {
    color: "#006DBC",
    // marginRight: 10,
    fontSize: 13
  },
  locationBox: {
    display: "flex",
    flexDirection: "row",
    marginBottom: 10,
    alignItems: "flex-start"
  },
  locationBoxImage: {
    width: 20,
    height: 20,
    resizeMode: "contain"
  },
  locationBoxFont: {
    marginLeft: 5,
    color: 'rgba(103, 103, 103, 1)'
  },
  timesBox: {
    display: "flex",
    flexDirection: "row",
    // marginTop: 10,
    justifyContent: "space-between"
  },
  timesViews: {
    display: "flex",
    flexDirection: "row"
  },
  timesViewsImage: {
    width: 20, height: 20,
    resizeMode: "contain"
  },
  timesViewsFont: {
    color: "rgba(0,0,0,0.4)",
    marginLeft: 5
  },
  likeCommentBox: {
    display: "flex",
    flexDirection: "row"
  },
  likeBox: {
    display: "flex",
    flexDirection: "row"
  },
  likeBoxImage: {
    width: 20,
    height: 20,
    resizeMode: "contain"
  },
  likeBoxFont: {
    color: "rgba(0,0,0,0.6)",
    marginLeft: 5
  },
  commentBox: {
    display: "flex",
    flexDirection: "row",
    marginLeft: 15
  },
  commentBoxImage: {
    width: 20,
    height: 20,
    resizeMode: "contain"
  },
  commentBoxFont: {
    color: "rgba(0,0,0,0.6)"
  },
  row: {
    flexDirection: "row",
    width: '100%',
    // justifyContent: 'flex-start',
    // alignContent: "flex-start",
    justifyContent: 'flex-start',
    flexWrap: "wrap",
    marginBottom: 10
  },
  labelRow: {
    flexDirection: "row",
    // justifyContent: "space-between",
    flexWrap: "wrap",
    marginBottom: 10,
    justifyContent: 'flex-start'
  },
  item: {
    flexDirection: "row",
    justifyContent: "space-between",
    width: '32%',
    // marginTop: 10,
    height: 100,
  },
  itemMr: {
    flexDirection: "row",
    justifyContent: "space-between",
    width: '32%',
    // marginTop: 10,
    marginRight: "2%",
    height: 100,
  },
  SystemPrompt: {
    width: "100%",
    height: 100,
  },
  statusBar: {
    width: width,
    height: statusBarHeight,
    backgroundColor: 'transparent',
  },
  bottom_container: {
    height: 100,
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  bottom_text: {
    color: "rgba(196, 196, 196, 1)"
  },
  IndicatorContainer: {
    alignItems: "center"
  },
})